package org.example.zpqy.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.zpqy.bean.WeatherResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Service
public class WeatherService {
    private static final Logger logger = LoggerFactory.getLogger(WeatherService.class);
    private static final String WEATHER_API_URL = "https://restapi.amap.com/v3/weather/weatherInfo?parameters";
    private static final String AMAP_API_KEY = "476fc756852a8caa003633f8074ffff5";
    private final ObjectMapper objectMapper = new ObjectMapper();
    public WeatherResponse getWeatherByDate(String city, String date) {
        String requestUrl = "https://restapi.amap.com/v3/weather/weatherInfo?city=" + city + "&date=" + date + "&key=" + AMAP_API_KEY;
        System.out.println("请求 URL: " + requestUrl); // 打印后检查 key 是否正确
        // 创建HTTP客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构建请求URL
            String url = String.format("%s?key=%s&city=%s&date=%s&extensions=all",
                    WEATHER_API_URL, AMAP_API_KEY, city, date);

            // 创建GET请求
            HttpGet httpGet = new HttpGet(url);

            // 执行请求并获取响应
            String response = httpClient.execute(httpGet, httpResponse ->
                    EntityUtils.toString(httpResponse.getEntity(), "UTF-8")
            );
            logger.info("高德天气API响应: {}", response);
            // 解析JSON响应
            return objectMapper.readValue(response, WeatherResponse.class);
        } catch (IOException e) {
            logger.error("获取天气信息失败", e);
            return null;
        }
    }
}
